/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package servlets;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import src.Command;
import src.Factory;
import src.ListaMensajes;
import src.ListaUsuarios;
import src.Usuario;

/**
 *
 * @author pabloavila
 */
public class Dispatcher extends HttpServlet {
   
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    Factory f;

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        // La session
        HttpSession session = request.getSession(false);
        String page = "/Viewer";
        try {

            // Miramos la accion que tenemos que realizar y nos venga por GET (links) o POST (forms)
            
            String lo = request.getParameter("action");
            if (lo != null && lo.equals("Logout")){
                session.setAttribute("action","Logout");
            }
            if (lo != null && lo.equals("AddUser")){
                session.setAttribute("action","AddUser");
                // Cogemos el resto de parametros: nombre de usuario
                String nombre = request.getParameter("name");
                session.setAttribute("add",nombre);                
            }

            if (lo != null && lo.equals("RemoveUser")){
                session.setAttribute("action","RemoveUser");
                // Cogemos el resto de parametros: nombre de usuario
                String nombre = request.getParameter("name");
                session.setAttribute("del",nombre);
            }

            if (lo != null && lo.equals("EditUser")){
                session.setAttribute("action","EditUser");
                // Cogemos el resto de parametros: nombre de usuario + permiso
                String nombre = request.getParameter("name");
                session.setAttribute("edit",nombre);
                String permis = request.getParameter("per");
                session.setAttribute("per",permis);
            }
            if (lo != null && lo.equals("Post")){
                session.setAttribute("action","Post");
                String texto = request.getParameter("texto");
                session.setAttribute("texto",texto);
            }
            
            // Cogemos todos los cacharros que tenemos que coger

            
            Usuario aux = (Usuario) session.getAttribute("ses_usr");
            f = new Factory(request,response);

            // Ahora a la factoria le pedimos los comandos

            // Creamos la frase que vamos a pedir: action_permisos
            String permisos = aux.getPermisos().toString();
            String action = (String) session.getAttribute("action");
            String frase = action + "_" + permisos;

            // Pedimos el comando
            Command c = f.getComando(frase);
            

            // Lo ejecutamos y se lo mandamos a viewer
            if (c != null) c.Execute();
            session.setAttribute("action", "");

            
            dispatch(request,response,page);

            
                        

        } catch (Exception e){
            page = "/index.jsp";
            // Pasarle los valores por request a viewer
            session.setAttribute("ses_notify",e.toString());
            session.setAttribute("ses_sign",false);
            dispatch(request,response,page);
        }

        finally {
            out.close();
        }
    }

    protected void dispatch(HttpServletRequest request,
        HttpServletResponse response,String page)
        throws  javax.servlet.ServletException, java.io.IOException {
        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(page);
        dispatcher.forward(request, response);
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
